import request from "./http.js"


//微信授权
const isWechat = function() {
	return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
}
//方法:用来提取code
const getUrlCode = function() {
	// return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [,
	// 		''
	// 	])[1]
	// 	.replace(/\+/g, '%20')) || null
	const data = getLocationSearch(location.href)
	uni.setStorageSync("shCode",data.shCode)
	// return decodeURIComponent(location.href.split('?')[1])
	// 	.split('&')
	// 	.map(item => item.split('='))
	// 	.reduce((acc, [key, value]) => {
	// 		acc[key] = value;
	// 		return acc;
	// 	}, {});
	return data
}
//检查浏览器地址栏中微信接口返回的code
const checkWeChatCode = async function() {
	let {code,shCode} = getUrlCode()
	if (code) {

		const gUser = await getOpenidAndUserinfo({code,shCode})
		if (gUser.status == 200) {
			afterLogin(gUser)
		}
	} else {
		
		await getWeChatCode(shCode)
	}
}
//请求微信接口，用来获取code
const getWeChatCode = function(shCode) {
	//let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址
	let local = window.location.href
	let appid = "wx3da9056cdd06e96c"
	// if(heatCompanyId==10){
	// 	//通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
	// 	appid = 'wxec3c64e99e173ace'
	// }else if(heatCompanyId==12){
	// 	appid = 'wx58bb63141b698429'
	// }
	// window.location.href =
	// 	"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
	// 	appid +
	// 	"&redirect_uri=" +
	// 	local +
	// 	"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
	request.post("/v1/user/toWxAuth",{shCode}).then(res=>{
		location.href = res.data
	})
		
}
//把code传递给后台接口，静默登录
const getOpenidAndUserinfo = async function(data) {
	return new Promise(function(reslove, reject) {
		request.post('v1/user/getUserOpenid', data).then((res) => {
			console.log(res)
			uni.hideLoading()
			if (res.status == 200) {
				
				reslove(res)
				return
			} else {
				reject(res)
				uni.showToast({
					title: res.msg,
					icon: 'none'
				});
			}
		})
	})

}
const getLocationSearch = function(link){
	var data = link.split('?')[1];
	let obj = null;
	if (link.indexOf('&') != -1) {
		obj = decodeURIComponent(data)
			.split('&')
			.map(item => item.split('='))
			.reduce((acc, [key, value]) => {
				acc[key] = value;
				return acc;
			}, {});
	} else {
		
		obj = [decodeURIComponent(data)]
			.map(item => item.split('='))
			.reduce((acc, [key, value]) => {
				acc[key] = value;
				return acc;
			}, {});
	
	}
	return obj
}
/*微信登录相关  end*/
const afterLogin = async function(res) {
	console.log('openid',res)
	// let user = res.data.user
	 uni.setStorageSync("openid", res.data.openid)

}
export {
	checkWeChatCode
}